package com.edu.dao.impl;

import com.edu.bean.Goods;
import com.edu.dao.BaseDao;
import com.edu.dao.GoodsDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther:zzp
 * @Date:2025/9/19-15:11:44
 */
public class GoodsDaoImpl implements GoodsDao {
    @Override
    public List<Goods> selectAllGoods(int pageNum, int pageSize) {
        List<Goods> goodsList = new ArrayList();
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet res = null;
        String sql = "SELECT * FROM goods LIMIT ?,?";
        try {
            con = BaseDao.getCon();
            ps = con.prepareStatement(sql);
            ps.setInt(1, (pageNum-1)*pageSize);
            ps.setInt(2, pageSize);
            res = ps.executeQuery();
            System.out.println(ps);
            while(res.next()) {
                Goods goods = new Goods();
                goods.setGoodsId(res.getInt("goodsId"));
                goods.setGoodsName(res.getString("goodsName"));
                goods.setGoodsFactory(res.getString("goodsFactory"));
                goods.setGoodsNum(res.getInt("goodsNum"));
                goods.setGoodsType(res.getString("goodsType"));
                goods.setGoodsPrice(res.getDouble("goodsPrice"));
                goodsList.add(goods);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            BaseDao.closeAll(res, ps, con);;
        }
        return goodsList;
    }

    @Override
    public int selectAllGoodsNum() {
        int rows = 0;
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet res = null;
        String sql = "SELECT count(1) as rom FROM goods";
        try {
            con = BaseDao.getCon();
            ps = con.prepareStatement(sql);
            res = ps.executeQuery();
            if(res.next()) {
                rows = res.getInt("rom");
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            BaseDao.closeAll(res, ps, con);;
        }
        return rows;
    }

    @Override
    public int deleteGoodById(int goodId) {
        Connection con = null;
        PreparedStatement ps = null;
        int result = 0;
        String sql = "DELETE FROM goods WHERE goodsId = ?";
        try {
            con = BaseDao.getCon();
            ps = con.prepareStatement(sql);
            ps.setInt(1,goodId);
            result = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDao.closeAll(null, ps, con);
        }

        return result;
    }
}
